package br.com.vemtransporte.telas;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import br.com.vemtransporte.basicas.Android;
import br.com.vemtransporte.basicas.Usuario;
import br.com.vemtransporte.fachada.Fachada;
import android.R.array;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

public class TelaCadastro extends Activity {
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
	public static final int MEDIA_TYPE_IMAGE = 1;
	public static final int MEDIA_TYPE_VIDEO = 2;
	private Uri fileUri;
	
	private HttpURLConnection conn = null;
	private DataOutputStream printout;
    private DataInputStream input;


	Button btSalvar, btVoltar;
	ImageButton btCam;
	EditText edtTxtNome, edtTxtEmail, edtTxtData, edtTxtSenha;
	Usuario usuario = new Usuario();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cadastro);


		edtTxtNome = (EditText) findViewById(R.id.editTextNome);
		edtTxtEmail = (EditText) findViewById(R.id.editTextEmail);
		edtTxtData = (EditText) findViewById(R.id.editTextDtNasc);
		edtTxtSenha = (EditText) findViewById(R.id.editTextSenhaCadastro);

		btCam = (ImageButton) findViewById(R.id.btCamera);
		btCam.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (checkCameraHardware(TelaCadastro.this)) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

					// fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

					fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create
																		// a
																		// file
																		// to
																		// save
																		// the
																		// image
					intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set
																		// the
																		// image
																		// file
																		// name
					
					intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0); // set the video image quality to high

					// start the image capture Intent
					startActivityForResult(intent,
							CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
					

				}

			}

		});

		btVoltar = (Button) findViewById(R.id.btVoltarCadastro);
		btVoltar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent voltar = new Intent(v.getContext(), TelaLogin.class);
				startActivity(voltar);
				finish();
			}
		});

		btSalvar = (Button) findViewById(R.id.btSalvarCadastro);
		btSalvar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				usuario.setNome(edtTxtNome.getText().toString());
				usuario.setEmail(edtTxtEmail.getText().toString());
				usuario.setData(edtTxtData.getText().toString());
				usuario.setSenha(edtTxtSenha.getText().toString());

				try {
					int retorno;
					retorno = Fachada.getInstance().cadastrarUsuario(usuario);
					if (retorno < 1) {
						Android.ShowMessage("Erro cadastrado!", v.getContext());
					} else {
						Android.ShowMessage("Cadastrado com sucesso!",
								v.getContext());
						edtTxtNome.setText("");
						edtTxtEmail.setText("");
						edtTxtData.setText("");
						edtTxtSenha.setText("");
					}
				} catch (Exception e) {
					Android.ShowMessage("Erro!", v.getContext());
				}
			}
		});
	}

	/** Check if this device has a camera */
	private boolean checkCameraHardware(Context context) {
		if (context.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_CAMERA)) {
			// this device has a camera
			return true;
		} else {
			// no camera on this device
			return false;
		}
	}

	private PictureCallback mPicture = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {

			File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
			if (pictureFile == null) {
				// ( "Error creating media file, check storage permissions: " +
				// e.getMessage());
				return;
			}

			try {
				FileOutputStream fos = new FileOutputStream(pictureFile);
				fos.write(data);
				fos.close();
			} catch (FileNotFoundException e) {
				// Log.d(TAG, "File not found: " + e.getMessage());
			} catch (IOException e) {
				// Log.d(TAG, "Error accessing file: " + e.getMessage());
			}
		}
	};

	/** Create a file Uri for saving an image or video */
	private static Uri getOutputMediaFileUri(int type) {
		return Uri.fromFile(getOutputMediaFile(type));
	}

	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(int type) {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"MyCameraApp");
		// This location works best if you want the created images to be shared
		// between applications and persist after your app has been uninstalled.

		// Create the storage directory if it does not exist
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
				return null;
			}
		}

		// Create a media file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_FOTOUSUARIO.jpg");
		} else if (type == MEDIA_TYPE_VIDEO) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "VID_" + timeStamp + ".mp4");
		} else {
			return null;
		}

		return mediaFile;
	}
	
	/** Converts the base64 encoded byte array <code>pValue</code>
	 * into a string.
	 */
	public static String encode(byte[] pValue) {
		return android.util.Base64.encodeToString(pValue, 0);
	}
	
	public static byte[] inputStreamToByteArray(InputStream inStream) throws IOException {
	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    byte[] buffer = new byte[8192];
	    int bytesRead;
	    while ((bytesRead = inStream.read(buffer)) > 0) {
	        baos.write(buffer, 0, bytesRead);
	    }
	    return baos.toByteArray();
	}
	
	/** Called when an activity called by using startActivityForResult finishes. */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    	
		String path = getOutputMediaFile(MEDIA_TYPE_IMAGE).getPath();

		try {
			
			InputStream is = new FileInputStream(path);
									
			
			byte[] isba = inputStreamToByteArray(is);
			
			
			String fotoString64 = encode(isba);			
		
			String parametrosServer = URLEncoder.encode("idUsuarioStr", "UTF-8") + "=" + URLEncoder.encode("5", "UTF-8") 
			+ "&" + URLEncoder.encode("foto", "UTF-8") + "=" + URLEncoder.encode(fotoString64, "UTF-8");			
			
		    
				URL url = new URL(
						"http://www.vemtransporte.com.br/ServiceData/UsuarioCadastrarFoto");
				
				conn = (HttpURLConnection)url.openConnection();
				conn.setDoOutput(true);
				conn.setDoInput(true);
				
				// We want no caching
			    conn.setUseCaches (false);
			 
			    // Specify the header content type.
			    //conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				
				//conn.connect();
				
				// Send POST output.
			    printout = new DataOutputStream (conn.getOutputStream ());
				
				
				//wr = new OutputStreamWriter(conn.getOutputStream());
				// Send data
			    printout.writeBytes(parametrosServer);	    
			    printout.flush();
			    printout.close ();/**/
			    
			    // Get response data.
			    input = new DataInputStream (conn.getInputStream ());
			    String str;
			    while (null != ((str = input.readLine())))
			    {
			    	System.out.println (str);
				}
			    input.close ();

			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }

}
